﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Agent
{
    public sealed class CartOperate
    {


        /// <summary>
        /// 读取购物车信息
        /// </summary>
        /// <returns></returns>
        public static List<string> Read()
        {
            return CartJson.CookieRead();

        }
        /// <summary>
        /// 删除单个商品
        /// </summary>
        /// <param name="productid"></param> 
        public static void Delete(int productid)
        {
            List<string> CartList = CartJson.CookieRead();
            if (CartList != null && CartList.Count > 0)
            {
                foreach (var item in CartList)
                {
                    if (item == productid.ToString())
                    {
                        CartList.Remove(item);
                        break;
                    }
                }
            }
            CartJson.CookieWrite(CartList);
        }
        /// <summary>
        /// 清空整个购物车
        /// </summary>
        public static void ClearCart()
        {
            HttpCookie shopcar = new HttpCookie(CartJson.CookieNameStr);

            shopcar.Expires = DateTime.Now.AddYears(-50);

            System.Web.HttpContext.Current.Response.Cookies.Add(shopcar);
            System.Web.HttpContext.Current.Request.Cookies.Remove(CartJson.CookieNameStr);


        }
        /// <summary>
        /// 添加一条商品到购物车
        /// </summary>
        /// <param name="model"></param
        public static void AddProductCart(int? ProductID)
        {
            if (ProductID.HasValue)
            {


                AddCart(ProductID.ToString());

            }
        }
        /// <summary>
        /// 添加一条商品到购物车
        /// </summary>
        /// <param name="model"></param>
        public static void AddCart(string model)
        {
            List<string> List = new List<string>();
            if (CartJson.ExistCookie())
            {
                List<string> CartList = CartJson.CookieRead();
                if (CartList != null && CartList.Count > 0)
                {
                    var m = CartList.Find(c => c == model);
                    if (m !=null)
                    {
                        CartList.Remove(m);
                        CartJson.CookieWrite(CartList);
                        return;
                    }
                    else
                    {
                        CartList.Add(model);
                        CartJson.CookieWrite(CartList);
                    }
                    

                }
               
                else
                {
                    List.Add(model);
                    CartJson.CookieWrite(List);
                }
            }
            else
            {
                List.Add(model);
                CartJson.CookieWrite(List);
            }

        }
    }
      

}